// API基础URL
const API_BASE_URL = 'http://localhost:8000'

// API请求函数
const apiRequest = async (url, options = {}) => {
  try {
    let finalUrl = url
    if (options.params && Object.keys(options.params).length > 0) {
      const searchParams = new URLSearchParams(options.params)
      finalUrl = `${url}?${searchParams.toString()}`
    }
    const response = await fetch(`${API_BASE_URL}${finalUrl}`, {
      headers: {
        'Content-Type': 'application/json',
        ...options.headers
      },
      ...options
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    return await response.json()
  } catch (error) {
    console.error('API请求失败:', error)
    throw error
  }
}

// 测试根路径
export const testRoot = async () => {
  try {
    const data = await apiRequest('/')
    console.log('根路径测试成功:', data)
    return data
  } catch (error) {
    console.error('根路径测试失败:', error)
    return null
  }
}

// 流式对话
export const streamChat = async (message, sessionId = null, callback = null) => {
  try {
    const response = await fetch(`${API_BASE_URL}/conversations/chat`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        message,
        session_id: sessionId
      })
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    let buffer = ''
    let result = ''

    while (true) {
      const { done, value } = await reader.read()
      if (done) break
      
      const chunk = decoder.decode(value, { stream: true })
      result += chunk
      buffer += chunk
      
      // 处理SSE格式：按行分割处理
      const lines = buffer.split('\n')
      buffer = lines.pop() || '' // 保留最后不完整的行
      
      for (const line of lines) {
        const trimmedLine = line.trim()
        if (!trimmedLine) continue // 跳过空行
        
        // 检查是否是数据行
        if (trimmedLine.startsWith('data: ')) {
          const dataStr = trimmedLine.slice(6) // 移除 "data: " 前缀
          if (dataStr) {
            try {
              const dataObj = JSON.parse(dataStr)
              const message = dataObj.message
              console.log('提取到的 message:', message)
              
              // 调用回调函数
              if (typeof callback === 'function') {
                callback(message)
              }
              
              // 检查是否是结束标记
              if (dataObj.is_finished) {
                console.log('流式对话结束')
              }
            } catch (e) {
              console.warn('解析流式数据失败，可能是数据不完整:', e.message)
              // 不抛出错误，继续处理后续数据
            }
          }
        }
      }
    }
    
    // 处理缓冲区中剩余的数据
    if (buffer.trim()) {
      const trimmedLine = buffer.trim()
      if (trimmedLine.startsWith('data: ')) {
        const dataStr = trimmedLine.slice(6)
        if (dataStr) {
          try {
            const dataObj = JSON.parse(dataStr)
            const message = dataObj.message
            console.log('最后提取到的 message:', message)
            
            if (typeof callback === 'function') {
              callback(message)
            }
          } catch (e) {
            console.warn('解析最后数据块失败:', e.message)
          }
        }
      }
    }

    return result
  } catch (error) {
    console.error('流式对话失败:', error)
    throw error
  }
}

// 普通对话（非流式）
export const chat = async (message, sessionId = null) => {
  try {
    const data = await apiRequest('/conversations/chat', {
      method: 'POST',
      body: JSON.stringify({
        message,
        session_id: sessionId
      })
    })
    return data
  } catch (error) {
    console.error('对话失败:', error)
    throw error
  }
}

// 获取对话列表
export const getConversationsList = async (params) => {
  try {
    const data = await apiRequest('/conversations/list', {
      method: 'GET',
      params
    })
    return data
  } catch (error) {
    console.error('获取对话列表失败:', error)
    return []
  }
}

// 删除对话
export const deleteConversation = async (sessionId) => {
  try {
    const data = await apiRequest('/conversations/delete', {
      method: 'GET',
      params: {
        session_id: sessionId
      }
    })
    return data
  } catch (error) {
    console.error('删除对话失败:', error)
    throw error
  }
}

// 获取对话详情
export const getConversationDetail = async (sessionId) => {
  try {
    const data = await apiRequest('/conversations/detail', {
      method: 'GET',
      params: {
        session_id: sessionId
      }
    })
    return data
  } catch (error) {
    console.error('获取对话详情失败:', error)
    throw error
  }
}

// 获取推荐问题
export const getRecommendedQuestions = async () => {
  try {
    const data = await apiRequest('/conversations/recommend-questions', {
      method: 'GET',
    })
    return data
  } catch (error) {
    console.error('获取推荐问题失败:', error)
    return []
  }
}

// 提交反馈
export const submitFeedback = async (messageId, isPositive, feedbackContent = '') => {
  try {
    const data = await apiRequest('/conversations/feedback', {
      method: 'POST',
      body: JSON.stringify({
        message_id: messageId,
        is_positive: isPositive,
        feedback_content: feedbackContent
      })
    })
    return data
  } catch (error) {
    console.error('提交反馈失败:', error)
    throw error
  }
}

// 默认导出所有API方法
export default {
  testRoot,
  streamChat,
  chat,
  getConversationsList,
  submitFeedback
}